package com.juphoon.mockdata.util;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.json.JsonReadFeature;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.util.Map;

/**
 * @author juphoon
 * @date 2022/4/2
 */
public class JsonHelper {
    ObjectMapper mapper;

    public JsonHelper() {
        mapper = new ObjectMapper();
        mapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                jsonGenerator.writeString("");
            }
        });
        mapper.configure(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(), true);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public String toJson(Object object) throws IOException {
        return mapper.writeValueAsString(object);
    }

    public <T> T fromJson(String json, Class<T> cls) throws IOException {
        return mapper.readValue(json, cls);
    }

    public <T> T fromJson(String json, TypeReference valueTypeRef) throws IOException {
        return (T) mapper.readValue(json, valueTypeRef);
    }

    public <T> T mapToBean(Map map, Class<T> cls) {
        return (T) mapper.convertValue(map, cls);
    }
}
